package com.fiberhome.nas.feature.main.view

import androidx.compose.animation.AnimatedContentScope
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalSharedTransitionApi
import androidx.compose.animation.SharedTransitionScope
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Upload
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRowDefaults.SecondaryIndicator
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.fiberhome.nas.core.designsystem.theme.AppTheme
import com.fiberhome.nas.core.designsystem.theme.CommonIcon
import com.fiberhome.nas.core.designsystem.theme.Primary
import com.fiberhome.nas.core.designsystem.theme.ShapeCircle
import com.fiberhome.nas.core.designsystem.theme.SpaceIndicator
import com.fiberhome.nas.core.designsystem.theme.SpacePaddingMedium
import com.fiberhome.nas.core.designsystem.theme.SpacePaddingSmall
import com.fiberhome.nas.core.designsystem.theme.TitleLarge
import com.fiberhome.nas.core.ui.component.appbar.CenterTopAppBar
import com.fiberhome.nas.core.ui.component.scaffold.AppScaffold
import com.fiberhome.nas.core.ui.component.text.AppText
import com.fiberhome.nas.feature.main.R
import com.fiberhome.nas.feature.main.model.TabDestination
import com.fiberhome.nas.feature.main.viewmodel.MainViewModel
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch

/**
 * 主界面路由入口
 */
@OptIn(ExperimentalSharedTransitionApi::class)
@Composable
internal fun MainRoute(
    sharedTransitionScope: SharedTransitionScope,
    animatedContentScope: AnimatedContentScope,
    viewModel: MainViewModel = hiltViewModel()
) {
    val editMode by viewModel.editMode.collectAsState()

    MainScreen(
        onBackClick = viewModel::navigateBack,
        onExitClick = viewModel::exitEditMode,
        onUploadClick = viewModel::navigateUpload,
        onTaskCenterClick = viewModel::navigateTaskCenter,
        onSettingClick = viewModel::navigateSetting,
        isEmpty = false,
        editMode = editMode,
        isAllSelected = false,
        selectedCount = 0
    )
}

/**
 * 主界面
 */
@OptIn(
    ExperimentalSharedTransitionApi::class, ExperimentalMaterial3Api::class
)
@Composable
internal fun MainScreen(
    sharedTransitionScope: SharedTransitionScope? = null,
    animatedContentScope: AnimatedContentScope? = null,
    onBackClick: () -> Unit = {},
    onExitClick: () -> Unit = {},
    onUploadClick: (index: Int) -> Unit = {},
    onTaskCenterClick: () -> Unit = {},
    onSettingClick: () -> Unit = {},
    isEmpty: Boolean,
    editMode: Boolean,
    isAllSelected: Boolean,
    selectedCount: Int,
) {
    // 协程作用域
    val scope = rememberCoroutineScope()
    // 声明共享的滚动状态
    val gridState = rememberLazyGridState()
    // 存储状态卡片 - 添加滚动显示/隐藏功能
    var isVisible by remember { mutableStateOf(true) }
    // 创建分页器状态
    val pagerState = rememberPagerState { TabDestination.entries.size }

    AppScaffold(
        backgroundColor = Color.White,
        topBar = {
            CenterTopAppBar(
                title = if (editMode) R.string.selected_item else R.string.nas,
                showBackIcon = !editMode,
                showExitIcon = editMode,
                onBackClick = onBackClick,
                onExitClick = onExitClick,
                actions = {
                    if (editMode) {
                        AppText(
                            modifier = Modifier.padding(end = SpacePaddingSmall),
                            text = if (isAllSelected) "取消全选" else "全选",
                            style = TitleLarge,
                            onClick = {

                            }
                        )
                    } else {
                        IconButton(onClick = {
                            //跳转到任务中心
                            onTaskCenterClick()
                        }) { CommonIcon(Icons.Filled.Upload) }
                        IconButton(onClick = {
                            //跳转到设置
                            onSettingClick()
                        }) { CommonIcon(Icons.Default.Settings) }
                    }
                })
        },
        floatingActionButton = {
            if (!editMode) {
                FloatingActionButton(
                    onClick = { onUploadClick(pagerState.currentPage) },
                    shape = ShapeCircle,
                    containerColor = Primary,
                    modifier = Modifier.size(48.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Add,
                        contentDescription = "上传",
                        tint = Color.White
                    )
                }
            }
        }
    ) { paddingValues ->
        Column {
            // 添加页面切换监听
            LaunchedEffect(pagerState.currentPage) {
                // 只有当页面真正切换时才执行回调
                if (editMode) {
                    onExitClick()
                }
            }

            // 监听滚动
            LaunchedEffect(gridState) {
                snapshotFlow {
                    Pair(
                        gridState.firstVisibleItemIndex,
                        gridState.firstVisibleItemScrollOffset
                    )
                }.distinctUntilChanged().collect { (currentIndex, currentOffset) ->
                    isVisible = currentIndex == 0 && currentOffset == 0
                }
            }

            // 带动画的存储状态卡片
            AnimatedVisibility(
                visible = isVisible && !editMode,
                enter = fadeIn() + slideInVertically(initialOffsetY = { -it }),
                exit = fadeOut() + slideOutVertically(targetOffsetY = { -it }),
            ) {
                FakeImage()
            }

            // 标签页
            ScrollableTabRow(
                selectedTabIndex = pagerState.currentPage,
                modifier = Modifier.padding(vertical = SpacePaddingMedium),
                containerColor = Color.Transparent,
                contentColor = MaterialTheme.colorScheme.onBackground,
                indicator = {
                    SecondaryIndicator(
                        Modifier.tabIndicatorOffset(it[pagerState.currentPage]),
                        SpaceIndicator
                    )
                },
                divider = {}
            ) {
                TabDestination.entries.forEachIndexed { index, title ->
                    Tab(
                        selected = pagerState.currentPage == index,
                        onClick = {
                            scope.launch {
                                pagerState.scrollToPage(page = index)
                            }
                        },
                        selectedContentColor = Primary,
                        unselectedContentColor = MaterialTheme.colorScheme.onBackground
                    ) {
                        Text(
                            text = stringResource(title.titleTextId),
                            style = TitleLarge,
                        )
                    }
                }
            }

            // 内容区域
            HorizontalPager(
                modifier = Modifier.fillMaxHeight(),
                state = pagerState,
                userScrollEnabled = !editMode
            ) {
                when (it) {
                    TabDestination.PHOTO.index -> PhotoRoute(gridState = gridState)
                    TabDestination.ALBUM.index -> AlbumRoute(gridState = gridState)
                    TabDestination.FILE.index -> PlaceholderContent(text = "文件功能开发中")
                }
            }
        }

    }

}

@Composable
private fun FakeImage() {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(120.dp)
            .clipToBounds(),
        contentAlignment = Alignment.Center
    ) {
        Image(
            painter = painterResource(id = R.drawable.ic_github),
            contentDescription = "假图片",
            modifier = Modifier
                .size(100.dp)
                .padding(16.dp)
        )
    }
}


@Composable
private fun PlaceholderContent(text: String) {
    Box(
        modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center
    ) {
        Text(
            text = text, fontSize = 18.sp, color = Color.Gray
        )
    }
}


@OptIn(ExperimentalSharedTransitionApi::class)
@Preview(showBackground = true)
@Composable
fun MainScreenPreview() {
    AppTheme {
        MainScreen(
            isEmpty = false, editMode = false, isAllSelected = false, selectedCount = 0
        )
        MainScreen(
            isEmpty = false, editMode = true, isAllSelected = false, selectedCount = 0
        )
    }
}
